package com.liu.qqRobot.poke.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.poke.entity.base.Poke;
import com.liu.mybatisPlus.poke.entity.base.PokeGroupUserPoke;
import com.liu.mybatisPlus.poke.service.PokeGroupUserPokeService;
import com.liu.mybatisPlus.poke.service.PokeService;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ReleasePokeHandler {

    @Resource
    private PokeGroupUserPokeService pokeGroupUserPokeService;

    @Resource
    private PokeService pokeService;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        String text = data.getText();
        String pokeName = text.replace("放生 ", "");
        QueryWrapper<PokeGroupUserPoke> pokeGroupUserPokeQueryWrapper = new QueryWrapper<>();
        pokeGroupUserPokeQueryWrapper.eq("group_id", groupId);
        pokeGroupUserPokeQueryWrapper.eq("user_id", userId);
        pokeGroupUserPokeQueryWrapper.eq("is_release", false);
        List<PokeGroupUserPoke> pokeGroupUserPokeList = pokeGroupUserPokeService.list(pokeGroupUserPokeQueryWrapper);
        List<Integer> pokeIdList = pokeGroupUserPokeList.stream().map(PokeGroupUserPoke::getPokeId).collect(Collectors.toList());
        List<Poke> pokeList = pokeService.listByIds(pokeIdList);
        Poke poke = pokeList.stream().filter(p -> p.getName().equals(pokeName)).findFirst().get();
        PokeGroupUserPoke pokeGroupUserPoke = pokeGroupUserPokeList.stream().filter(p -> p.getPokeId().equals(poke.getId())).findFirst().get();
        pokeGroupUserPoke.setIsRelease(true);
        pokeGroupUserPokeService.updateById(pokeGroupUserPoke);
        String msg = "[CQ:at,qq=" + userId + "]\n你已经放生宝可梦：" + pokeName;
        QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
        qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.RELEASE_POKE);
    }

}
